package com.efun.center.http.config;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceFactoryBean<T> implements FactoryBean<T>, InitializingBean {

	/**
	 * 服务接口
	 */
	protected Class<T> service;

	/**
	 * 管理器
	 */
	protected ProjectLoader projectLoader;

	/**
	 * 服务接口代理
	 */
	protected T serviceProxy;

	public ServiceFactoryBean() {
	}

	public ServiceFactoryBean(Class<T> service) {
		this.service = service;
	}

	public void setProjectLoader(ProjectLoader projectLoader) {
		this.projectLoader = projectLoader;
	}

    @Override
	public T getObject() throws Exception {
		return serviceProxy;
	}

    @Override
	public Class<T> getObjectType() {
		return service;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

    @Override
	@SuppressWarnings("unchecked")
	public void afterPropertiesSet() throws Exception {
		// 创建调用器
		ProjectInvoker projectInvoker = new ProjectInvoker(projectLoader, service);

		// 创建代理
		serviceProxy = (T) Proxy.newProxyInstance(ProjectLoader.class.getClassLoader(),
				new Class[] {service}, new InvocationHandler() {

					public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
						return projectInvoker.invoke(method, params);
					}

				}
		);
	}

}
